package com.project.collectAPI.comm;

import com.alibaba.druid.util.StringUtils;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class AutoRobot {

    /**
     * 窗口移动
     * @param lowNum 低位 0.2
     * @param HightNum 高位 0.4
     * */
    public static int delayTime(Double lowNum,Double HightNum){
        Random random = new Random();
        //double atime = 0.2 +random.nextDouble()*(0.4-0.2);
        double atime = lowNum +random.nextDouble()*(HightNum-lowNum);
        atime*=1000;
        return (int)atime;
    }


    /**
     * 昌大昌-鹰展店
     *          String cdc="昌大昌-鹰展店";
     *         char[] strArr=cdc.toCharArray();
     *         AutoRobot.WriteText(strArr);
     **/
    public static void WriteText(char[] Text) throws AWTException {
        Robot robot=new Robot();
        try {
            /*char abc[]=new char[6];
            abc[0]='W';
            abc[1]='O';
            abc[2]='A';
            abc[3]='I';
            abc[4]='N';
            abc[5]='I';*/
            for(char k : Text){
                robot.keyPress((byte)k);
                robot.keyRelease((byte)k);
                robot.delay(200);
                robot.keyPress(KeyEvent.VK_SPACE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    /**
     *      复制粘贴
     *          String cdc="昌大昌-鹰展店";
     *         AutoRobot.setsysclipboardText(cdc);
     *         robot.delay(1000);
     *         robot.keyPress(KeyEvent.VK_CONTROL);
     *         robot.keyPress(KeyEvent.VK_V);
     *         robot.delay(10);
     *         robot.keyRelease(KeyEvent.VK_CONTROL);
     *         robot.keyRelease(KeyEvent.VK_V);
     * */
    public static void WriteText(Robot robot,String Text) throws AWTException {
        AutoRobot.setsysclipboardText(Text);
        robot.delay(1000);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.delay(10);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_V);
    }





    /**
     * 设置粘贴板
     **/
    public static void setsysclipboardText(String writeMe){
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable wtext = new StringSelection(writeMe);
        clip.setContents(wtext,null);
    }
    /**
     * 获取粘贴板
     **/
    public static String getsysclipboardText(){
        String ret = "";
        Clipboard sysclip = Toolkit.getDefaultToolkit().getSystemClipboard();//获取剪切板中的内容
        Transferable clipTf = sysclip.getContents(null);
        if (clipTf != null) {
            //检查内容是否是文本类型
            if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                try {
                    ret = (String) clipTf.getTransferData(DataFlavor.stringFlavor);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }


    /**
     * 获取窗口句柄
     * */
    //利用嗅探工具查看句柄
    public static WinDef.HWND getWindowHandle(String className, String windowTitle) {
        WinDef.HWND hwnd = User32.INSTANCE.FindWindow(className, windowTitle);
        if(hwnd!=null) {
            for (int i = 0; i < 2; i++) { //循环2次确保程序在最顶端
                User32.INSTANCE.SetForegroundWindow(hwnd); //设置窗口在最顶层
            }
        }
        return hwnd;
    }

    /**
     * 窗口移动
     * @param handle 获取到的窗口句柄
     * @param posX 鼠标x坐标
     * @param posY 鼠标Y坐标
     * @param winWidth 移动后窗体的宽度
     * @param winHeight 移动后窗体高度
     * @param isPain 移动后是否重绘对象
     * */
    //调用函数移动窗体 415,780,
    public static void moveWindowHandle(WinDef.HWND handle,int posX,int posY,int winWidth,int winHeight,boolean isPain) {
        User32.INSTANCE.MoveWindow(handle,posX,posY,winWidth,winHeight,false);
    }


    /**
     * 启动程序
     * @param robot 机器人对象
     * */
    public static WinDef.HWND StartProgram(Robot robot,String Programexe,String Programparas,String className,String windowTitle) throws InterruptedException, IOException {
        //打开程序 --无参数启动
        //Runtime.getRuntime().exec( "cmd.exe /c start \"C:\\Program Files\\Tencent\\WeChat\\xxx.exe\" );

        //打开小程序 -- 有参数启动
        Process start = Runtime.getRuntime().exec(new String[]
                //D:\Windows\WeChat\WechatAppLauncher.exe -launch_appid=wxffb7d80f8c50ac5c //李总启动目标位置
                //"C:\Program Files\Tencent\WeChat\WechatAppLauncher.exe" -launch_appid=wxffb7d80f8c50ac5c
                {Programexe, Programparas});

        //等待5秒
        TimeUnit.SECONDS.sleep( 3);

        //利用嗅探工具查看句柄
        //WinDef.HWND handle = AutoRobot.getWindowHandle("Chrome_WidgetWin_0", "饿了么 l 外卖美食超市买菜水果");
        WinDef.HWND handle = AutoRobot.getWindowHandle(className, windowTitle);
        start=null;
        return handle!=null?handle:null;
    }




    /**
     * 鼠标移动
     * @param robot 机器人对象
     * */
    public static void MouseMove(Robot robot,int pointX,int pointY) throws InterruptedException {
        robot.mouseMove(pointX,pointY); //释放鼠标
        robot.delay(1000);
    }


    /**
     * 鼠标点击
     * @param robot 机器人对象
     * */
    public static void MouseClick(Robot robot) throws InterruptedException {
        for (int i = 0; i < 4; i++) {
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); //点击店铺
            TimeUnit.MILLISECONDS.sleep(10);
        }
        robot.delay(AutoRobot.delayTime(0.2,0.4));
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); //释放鼠标
    }

    /**
     * 复制粘贴操作
     * @param robot 机器人对象
     * */
    public static void CopyPaste(Robot robot){
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.delay(AutoRobot.delayTime(0.2,0.4));
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_V);
    }

    /**
     * 抓图对比
     * */
    public static void FindCloseX(Robot robot) throws IOException {
        BufferedImage current = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        int X_START=0;
        int Y_START=0;
        String path="src/main/resources/static/images/screenShot/imgFile/";
        String[] chaArr=new String[]{"cha1.png","cha2.png"};
        for (int i = 0; i < chaArr.length; i++) { //查找所有交叉
            String filePath=path+chaArr[i];
            if(!StringUtils.isEmpty(filePath)){
                BufferedImage icon = ImageIO.read(new File(filePath));
                for (int x = 0; x < current.getWidth (); x++){ //逐个像素对比查找
                    for (int y = 0; y < current.getHeight(); y++) //逐个像素对比查找
                    {
                        boolean matches = true;
                        for (int x2 = 0; x2 < icon.getWidth () && matches; x2++)
                            for (int y2 = 0; y2 < icon.getHeight() && matches; y2++) {
                                //System.out.println("寻找弹窗交叉坐标:"+icon.getRGB(x2, y2)+","+ current.getRGB(x + x2, y + y2));
                                if (icon.getRGB(x2, y2) != current.getRGB(x + x2, y + y2))
                                    matches = false;
                            }
                        if (matches)
                        {
                            X_START = x;
                            Y_START = y;
                            System.out.println("找到坐标:"+X_START+","+Y_START);
                            return;
                        }
                        //System.out.println("寻找坐标:"+X_START+","+Y_START);
                    }
                }
            }
        }
    }

    /**
     * 查找店铺
     * @param Dir 0 左上角  1 右下角
     * */
    public static Point findStore(Robot robot,String imgName,int Dir) throws IOException {
        int loop=0;
        boolean flag=true;
        Point point;
        while (flag){
            if(loop>2){ //最多循环3次
                flag=false;
                return null;
            }
            if(Dir==0){ //从左上角开始搜索
                point=AutoRobot.compareStoreImgFormLeftTop(robot,imgName);
            }else{ //从左下角开始搜索
                point=AutoRobot.compareStoreImgFormRightBottom(robot,imgName);
            }

            if(point.x!=-1 && point.y!=-1){
                flag=false;
                return point;
            }else{
                //没有找到，鼠标中间滚一下
                robot.mouseWheel(1);
            }
            loop++;
        }
        return null;
    }

    /**
     * 查找店铺对比图_从左上角开始查找
     * */
    public static Point compareStoreImgFormLeftTop(Robot robot,String StoreImgName) throws IOException {
        //BufferedImage current = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        BufferedImage current = robot.createScreenCapture( new Rectangle(0, 0, 520,880)); //+100像素,免除RGB像素查找超出边界
        int X_START=0;
        int Y_START=0;
        Point point=new Point();
        point.x=-1;
        point.y=-1;
        boolean isFind=false;
        String filePath="src/main/resources/static/images/screenShot/imgFile/"+StoreImgName;
            if(!StringUtils.isEmpty(filePath)){
                BufferedImage icon = ImageIO.read(new File(filePath));
                for (int x = 0; x < current.getWidth(); x++){ //逐个像素对比查找
                    if(isFind){
                        return point;
                    }
                    for (int y = 0; y < current.getHeight(); y++) //逐个像素对比查找
                    {
                        boolean matches = true;
                        for (int x2 = 0; x2 < icon.getWidth() && matches; x2++)
                            for (int y2 = 0; y2 < icon.getHeight() && matches; y2++) {
                                //System.out.println("寻找目标图片坐标:"+icon.getRGB(x2, y2)+","+ current.getRGB(x + x2, y + y2));
                                if (icon.getRGB(x2, y2) != current.getRGB(x + x2, y + y2))
                                    matches = false;
                            }
                        if (matches)
                        {
                            X_START = x;
                            Y_START = y;

                            point.x=x;
                            point.y=y;
                            System.out.println("找到坐标:"+X_START+","+Y_START);

                            isFind=true;
                            return point;
                        }
                        //System.out.println("寻找坐标:"+X_START+","+Y_START);
                    }
                }
        }
        /*System.out.println("删除图片");
        //--不删除可以查看抓取的图片分析数据
        FileUtils.deleteLocalServerImage(namePic); */
        return point;
    }


    /**
     * 查找店铺对比图_从右下角开始查找
     * */
    public static Point compareStoreImgFormRightBottom(Robot robot,String StoreImgName) throws IOException {
        //BufferedImage current = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        BufferedImage current = robot.createScreenCapture(new Rectangle(0,0,520,880)); //+100像素,免除RGB像素查找超出边界
        int X_START=0;
        int Y_START=0;
        Point point=new Point();
        point.x=-1;
        point.y=-1;
        boolean isFind=false;
        String filePath="src/main/resources/static/images/screenShot/imgFile/"+StoreImgName;
        if(!StringUtils.isEmpty(filePath)){
            BufferedImage icon = ImageIO.read(new File(filePath));
            for (int x = current.getWidth()-1; x >0; x--){ //逐个像素对比查找
                if(isFind){
                    return point;
                }
                for (int y = current.getHeight()-1; y >0; y--) //逐个像素对比查找
                {
                    boolean matches = true;
                    for (int x2 = 0; x2 < icon.getWidth() && matches; x2++)
                        for (int y2 = 0; y2 < icon.getHeight() && matches; y2++) {
                            /*System.out.println("x="+x+",y="+y);
                            System.out.println("x2="+x2+",y2:"+y2);
                            System.out.println("=================");
                           */
                            /*System.out.println(icon.getRGB(x2, y2));
                            System.out.println(current.getRGB(x-x2, y-y2));*/
                            System.out.println("寻找目标图片坐标:"+icon.getRGB(x2,y2)+","+ current.getRGB(x+x2, y+y2));
                            if (icon.getRGB(x2, y2) != current.getRGB(x+x2, y+y2))
                                matches = false;
                        }
                    if (matches)
                    {
                        X_START = x;
                        Y_START = y;

                        point.x=x;
                        point.y=y;
                        System.out.println("找到坐标:"+X_START+","+Y_START);

                        isFind=true;
                        return point;
                    }
                }
            }
        }
        return point;
    }





    public static Point compareImageFindPoint(Robot robot,int px,int py,int RectangleWidth,int RectangleHeight,String ImgName) throws IOException {
        BufferedImage current = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        //BufferedImage current = robot.createScreenCapture(new Rectangle(px, py, RectangleWidth,RectangleHeight)); //+100像素,免除RGB像素查找超出边界
        int X_START=0;
        int Y_START=0;
        Point point=new Point();
        point.x=-1;
        point.y=-1;
        boolean isFind=false;
        String filePath="src/main/resources/static/images/screenShot/imgFile/item/"+ImgName;
        if(!StringUtils.isEmpty(filePath)){
            BufferedImage icon = ImageIO.read(new File(filePath));
            for (int x = 0; x < current.getWidth(); x++){ //逐个像素对比查找
                if(isFind){
                    return point;
                }
                for (int y = 0; y < current.getHeight(); y++) //逐个像素对比查找
                {
                    boolean matches = true;
                    for (int x2 = 0; x2 < icon.getWidth() && matches; x2++)
                        for (int y2 = 0; y2 < icon.getHeight() && matches; y2++) {
                            //System.out.println("寻找目标图片坐标:"+icon.getRGB(x2, y2)+","+ current.getRGB(x + x2, y + y2));
                            if (icon.getRGB(x2, y2) != current.getRGB(x + x2, y + y2)) //x + x2, y + y2
                                matches = false;
                        }
                    if (matches)
                    {
                        X_START = x;
                        Y_START = y;

                        point.x=x;
                        point.y=y;
                        System.out.println("找到坐标:"+X_START+","+Y_START);

                        isFind=true;
                        return point;
                    }
                    //System.out.println("寻找坐标:"+X_START+","+Y_START);
                }
            }
        }
        /*System.out.println("删除图片");
        //--不删除可以查看抓取的图片分析数据
        FileUtils.deleteLocalServerImage(namePic); */
        return point;
    }


    /**
     * 鼠标中间上下滚动
     * @param Dir 0 向下滚动  1 向上滚动
     * */
    public static void MouseWheel(Robot robot,int Dir){
        if(Dir==0){
            robot.mouseWheel(2);
        }else{
            robot.mouseWheel(-2);
        }
    }



    //最后分类出现位置最新
    //需要提前截图准备好 lastclass.png 图片
    //targetImageName  "lastclass.png" = "src/main/resources/static/images/screenShot/imgFile/item/"
    public static Point FindTargetImagePositon(Robot robot,String targetImageName){
        Point findPoint=null;
        try {
            //查找坐标
            findPoint=AutoRobot.compareImageFindPoint(robot,0,0,100,580,targetImageName);
            if(findPoint!=null && (findPoint.x!=-1 && findPoint.y!=-1)){
                return findPoint;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return findPoint;
    }


    //分类最后出现位置(已废弃)
    public static Point isLastClassAppear(Robot robot){

        Point findPoint=null;

        //移动位置到置顶
        robot.mouseMove(260,370);
        robot.delay(1000);
        robot.mouseWheel(-100);
        robot.delay(1000);
        robot.mouseMove(36,376);
        robot.delay(1000);
        robot.mouseWheel(-100);
        robot.delay(1000);

        String picName="";
        int diff=50;
        int topY=220;

        Point point=new Point();
        point.x=3;
        point.y=topY;
        int RectWidth=80;
        int RectHeight=0;

        try {
            for (int i = 0; i < 19; i++) {
                if(i==2){
                    diff=60; //大品牌补贴
                }else{
                    diff=47;
                    if(i==9) diff=35;
                }
                RectHeight=diff;
                if(i==10){
                    point.y=topY;
                    robot.mouseWheel(9); //翻到下一页
                    robot.delay(1000);
                   /* String lastPic=picName;
                    System.out.println("补抓的最后一张图片名称"+picName);*/
                    //查找坐标
                    findPoint=AutoRobot.compareImageFindPoint(robot,0,topY,100,580,"lastclass.png");
                    if(findPoint!=null && (findPoint.x!=-1 && findPoint.y!=-1)){
                        System.out.println("找到最后一张分类图:"+findPoint.x+","+findPoint.y);
                        robot.mouseMove(findPoint.x,findPoint.y);
                        robot.delay(1000);
                    }else{
                        System.out.println("没有找到坐标");
                    }
                }
                //picName=SpiderTools.meituanScreenShot("item",point,RectWidth,RectHeight,false,false);
                point.y+=diff;
                try { TimeUnit.MILLISECONDS.sleep( 100); } catch (InterruptedException e) { e.printStackTrace(); }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //删除截图的数据
            /*String delPath="src/main/resources/static/images/screenShot/imgFile/item/";
            AutoRobot.deleteImg(new File(delPath));*/
        }
        return findPoint;
    }






    /**
     * 归删除某个文件夹下所有的图片
     * @param 示例 deleteImg(new File("d:\\a"));
     * */
    public static void deleteImg(File file) {
        if (file != null) {
            if (file.isDirectory()) {
                String[] list = file.list();
                if (list != null && list.length > 0) {
                    for (String s : list) {
                        File file1 = new File(file, s);
                        deleteImg(file1);
                        String[] strs = s.split("\\.");
                        if (strs.length > 0) {
                            String type = strs[strs.length - 1];
                            if (type.equals("png") || type.equals("jpg") || type.equals("jpeg")) {
                                boolean b = file1.delete();
                                //System.out.println("移除"+file1.getAbsolutePath() + "\t" + b);
                            }
                        }
                    }
                    System.out.println("移除所有菜单分类截图...");
                }
            }
        }
    }


} //Class End
